<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket客户端</title>
</head>
<body>
<script type="text/javascript">
    var socket;
    var id = 'lisi';
    //如果浏览器支持WebSocket
    if (window.WebSocket) {
        //参数就是与服务器连接的地址
        socket = new WebSocket("ws://127.0.0.1:5005/ws");

        //客户端收到服务器消息的时候就会执行这个回调方法
        socket.onmessage = function (event) {
            console.log(event);
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + event.data;
        }

        //连接建立的回调函数
        socket.onopen = function (event) {
            var rt = document.getElementById('responseText');
            rt.value = '连接开启了...';
            console.log('连接开启了。。。');
            // 注册用户
            registerUser();
        }

        //连接断掉的回调函数
        socket.onclose = function (event) {
            var rt = document.getElementById('responseText');
            rt.value = '连接关闭了...';
        }
    } else {
        alert("浏览器不支持WebSocket！");
    }

    //发送数据
    function send(message) {
        if (!window.WebSocket) {
            return;
        }

        //当websocket状态打开
        if (socket.readyState == window.WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("连接没有开启");
        }
    }

    /**
     * 注册用户
     */
    function registerUser() {
        var options = {
            "id": id,
            "type": "single"
        };
        var op = JSON.stringify(options);
        socket.send(op);
    }
</script>
<form onsubmit="return false">
    <textarea name="message" style="width: 400px;height: 200px"></textarea>

    <input type="button" value="发送数据" onclick="send(this.form.message.value);">

    服务器输出：

    <textarea id="responseText" style="width: 400px;height: 300px;"></textarea>

    <input type="button" onclick="javascript:document.getElementById('responseText').value=''" value="清空数据">
</form>
</body>
</html>